package com.bwie.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.Menu;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Override
    public R login(LoginVo loginVo) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName, loginVo.userName));
        if(user==null){
            return R.error().setMsg("用户不存在");
        }

        String encrypt = MD5Utils.encrypt(loginVo.getUserPass());
        System.out.println("加密的密码:"+encrypt);
        if(!user.getUserPass().equals(encrypt)){
            return R.error().setMsg("密码不正确");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", user.getUserId()).claim("userName",user.getUserName()).compact();
        String key = "token-" + user.getUserId();
        redisTemplate.opsForValue().set(key,token,60, TimeUnit.MINUTES);

        user.setToken(token);
        return R.ok().setData(user);
    }

    @Override
    public R getMenuTree() {
        String token = request.getHeader("token");
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        List<Menu> menuList=userMapper.getMenuTree(userId);

        List<Tree<String>> treeList = TreeUtil.build(menuList, "0", (menu, treeNode) -> {
            treeNode.setName(menu.getMenuName());
            treeNode.setId(menu.getMenuId().toString());
            treeNode.setParentId(menu.getMenuPid().toString());
            treeNode.putExtra("path", menu.getMenuPath());
        });
        return R.ok().setData(treeList);
    }

    @Override
    public R getUserList(PageInfoVo pageInfoVo) {
        Page<User> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(User::getCreateTime);
        Page<User> userPage = userMapper.selectPage(page, wrapper);
        return R.ok().setData(userPage);
    }

    @Override
    public R getUserInfo() {
        String token = request.getHeader("token");
        if(token==null){
            return R.error().setMsg("请先登录");
        }
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        User user = userMapper.selectById(userId);

        List<String> roleNames=userMapper.getRoleByUserId(userId);

        StringBuilder stringBuilder = new StringBuilder();
        for (String roleName : roleNames) {
            if(stringBuilder.length()>0){
                stringBuilder.append(",").append(roleName);
            }else{
                stringBuilder.append(roleName);
            }
        }
        user.setRoleName(stringBuilder.toString());


        //脱敏
        user.setUserPass(null);
        user.setToken(token);
        return R.ok().setData(user);
    }

    @Override
    public R getUserInfoById(Integer userId) {
        User user = userMapper.selectById(userId);
        if(user==null){
            return R.error().setMsg("用户不存在");
        }


        return R.ok().setData(user);
    }

    @Override
    public R userSign() {
        String token = request.getHeader("token");
        if(token==null){
            return R.error().setMsg("请先登录");
        }
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        User user = userMapper.selectById(userId);
        if(user==null){
            return R.error().setMsg("用户不存在");
        }

        //签到送积分
        int score = RandomUtil.randomInt(10, 100);
        user.setUserScore(user.getUserScore()+score);
        userMapper.updateById(user);

        return R.ok().setMsg("签到成功,赠送"+score+"积分").setData(user);
    }

    @Override
    public R joinActiveSubScore(Integer userId, Integer score) {
        //获取用户信息
        User user = userMapper.selectById(userId);
        if(user==null){
            return R.error().setMsg("用户不存在");
        }
        //减积分
        if(user.getUserScore()<score){
            return R.error().setMsg("积分不足");
        }

        user.setUserScore(user.getUserScore()-score);
        userMapper.updateById(user);
        return R.ok();
    }
}
